//
//  RepairViewController.m
//  Mahjong
//
//  Created by mc on 16/9/8.
//  Copyright © 2016年 Elliot. All rights reserved.
//

#import "RepairViewController.h"
#import "ButtonAndLabels.h"
#import "AddDescribeViewController.h" //添加文字描述
#import "OrderManageViewController.h" //订单管理
#import "ZYQAssetPickerController.h"
#import "HCSStarRatingView.h"
#import "AddressViewController.h"
#import "Header.h"

#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
@interface RepairViewController ()<ButtonAndLabelsDelegate,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>

{
    NSString *addressString;
    UIView               *_editv;
    UILabel              *starLabel;
    UIButton             *_addPic;
    NSMutableArray       *_imageArray;
    UITextView *textVi;
    UILabel *alable;
    NSInteger num;
}
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UIView *textBackView;
@property (nonatomic, strong) UIView *btmView;

@end

@implementation RepairViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithWhite:0.900 alpha:1.000];
//    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.translucent = NO;
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"MRAddress"]);
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"MRAddress"] != nil) {
        addressString = [NSString stringWithFormat:@"%@ %@ %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"MRName"],[[NSUserDefaults standardUserDefaults] objectForKey:@"MRTel"],[[NSUserDefaults standardUserDefaults] objectForKey:@"MRAddress"]];
    }

    
    _imageArray = [NSMutableArray array];
    
    
//    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
//    [self.view addSubview:scrollView];
//    scrollView.contentSize = CGSizeMake(WIDTH, HEIGHT *3/2);
    
    
    [self addButtonAndLabelViews];
    [self addRepairResultUI];
    [self addAddressUI];
    [self sendRepairUI];
    [self addView];
    self.navigationItem.title = @"维修";
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_but_back"] style:(UIBarButtonItemStyleDone) target:self action:@selector(backAction)];
    backItem.tintColor = [UIColor grayColor];
    self.navigationItem.leftBarButtonItem = backItem;
    
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)addView{
    
    self.btmView = [[UIView alloc] initWithFrame:CGRectMake(0, 1000, SCREEN_WIDTH, SCREENH_HEIGHT/11*5)];
    self.btmView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.btmView];
    UIButton *ala =  [UIButton buttonWithType:UIButtonTypeCustom];
    ala.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT/12) ;
    [ala setTitle:@"转盘坏了,麻将机不能洗牌" forState:UIControlStateNormal];
    [ala setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btmView addSubview:ala];
    [ala addTarget:self action:@selector(label:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *bla =  [UIButton buttonWithType:UIButtonTypeCustom];
    bla.frame = CGRectMake(0, SCREENH_HEIGHT/12, SCREEN_WIDTH, SCREENH_HEIGHT/12) ;
    [bla setTitle:@"我的麻将机卡住了,摆不了牌" forState:UIControlStateNormal];
    [bla setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btmView addSubview:bla];
    [bla addTarget:self action:@selector(label:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *cla =  [UIButton buttonWithType:UIButtonTypeCustom];
    cla.frame = CGRectMake(0, SCREENH_HEIGHT/12*2, SCREEN_WIDTH, SCREENH_HEIGHT/12) ;
    [cla setTitle:@"弹簧报废,需要换修" forState:UIControlStateNormal];
    [cla setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btmView addSubview:cla];
    [cla addTarget:self action:@selector(label:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *dla =  [UIButton buttonWithType:UIButtonTypeCustom];
    dla.frame = CGRectMake(0, SCREENH_HEIGHT/12*3, SCREEN_WIDTH, SCREENH_HEIGHT/12) ;
    [dla setTitle:@"麻将机桌子腿瘸了,需要换修" forState:UIControlStateNormal];
    [dla setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btmView addSubview:dla];
    [dla addTarget:self action:@selector(label:) forControlEvents:UIControlEventTouchUpInside];

    UILabel *la = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 3)];
    la.backgroundColor = [UIColor lightGrayColor];
    [self.btmView addSubview:la];
    
    
}
-(void)label:(UIButton *)btn{
    textVi.text  = btn.titleLabel.text;
    self.btmView.frame = CGRectMake(0, 1000, 1, 1);
}
// 订单管理
#pragma mark -- 第二部分控件
- (void)addButtonAndLabelViews{
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backView.frame) +10, WIDTH, HEIGHT / 20)];
    lable.backgroundColor = [UIColor whiteColor];
    lable.text = @"订单管理";
    lable.font = [UIFont systemFontOfSize:17];
    lable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lable];
    
    NSInteger k = 0;
    NSArray *imageArray = @[@"service_but_notaccepted", @"service_but_price", @"service_but_notfinish", @"service_but_finish"];
    
    NSArray *titleArr = @[@"待受理", @"已报价", @"待完成", @"已完成"];
    
    for (NSInteger j=0; j<4; j++) {
        ButtonAndLabels *buttonViews = [[ButtonAndLabels alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width/4 )*j, CGRectGetMaxY(lable.frame) + 2, [UIScreen mainScreen].bounds.size.width/4 , [UIScreen mainScreen].bounds.size.width/4)];
        buttonViews.delegate = self;
        buttonViews.tag = 2000+k;
        buttonViews.backgroundColor = [UIColor whiteColor];
        
        buttonViews.FirstLabel.text = titleArr[k];
        buttonViews.BtnImageview.image = [UIImage imageNamed:imageArray[k]];
        k++;
        [self.view addSubview:buttonViews];
    }
    
}
//新控件的点击事件
- (void)buttonViewbtnClick:(UIButton *)button {
//    NSLog(@"%ld",(long)button.superview.tag);
    OrderManageViewController *orderManageVC = [[OrderManageViewController alloc] init];
        orderManageVC.buttonNumber = button.superview.tag;
    [self.navigationController pushViewController:orderManageVC animated:YES];    
}
// 维修发布
-(void)addRepairResultUI{
    UILabel *repairLable = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backView.frame) +22 + HEIGHT/20 + [UIScreen mainScreen].bounds.size.width/4 , WIDTH, HEIGHT / 20)];
    repairLable.backgroundColor = [UIColor whiteColor];
    repairLable.text = @"维修发布";
    repairLable.font = [UIFont systemFontOfSize:17];
    repairLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:repairLable];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(repairLable.frame) +2 , WIDTH, HEIGHT / 20)];
    lable.backgroundColor = [UIColor whiteColor];
    lable.text = @"  添加需要维修物品的照片(最多六张)";
    lable.textColor = [UIColor colorWithWhite:0.500 alpha:1.000];
    lable.font = [UIFont systemFontOfSize:15];
//    lable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lable];
    
    
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lable.frame)+2, WIDTH, HEIGHT / 4)];
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];

    // 评论 + 照片
    _editv = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lable.frame)+2, WIDTH, HEIGHT / 4)];
    _editv.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_editv];

    
    // + pic
    _addPic = [UIButton buttonWithType:UIButtonTypeCustom];
    _addPic.frame = CGRectMake(10, 15, 70, 70);
    [_addPic setImage:[UIImage imageNamed:@"service_but_addpicture@2x"] forState:UIControlStateNormal];
    [_addPic addTarget:self action:@selector(imageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    _addPic.tag = 3000;
    [_editv addSubview:_addPic];

//    UIButton *imageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    imageBtn.frame = CGRectMake(10, 15, );
//    [imageBtn addTarget:self action:@selector(imageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    imageBtn.backgroundColor = [UIColor whiteColor];
//    [imageBtn setImage:[UIImage imageNamed:@"service_but_addpicture"] forState:UIControlStateNormal];
//    imageBtn.tag = 3000;
//    [backView addSubview:imageBtn];
    
    UILabel *textLable = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(backView.frame) +2 , WIDTH, HEIGHT / 20)];
    textLable.backgroundColor = [UIColor whiteColor];
    textLable.text = @"  添加文字描述";
    textLable.textColor = [UIColor colorWithWhite:0.500 alpha:1.000];
    textLable.font = [UIFont systemFontOfSize:15];
    //    lable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:textLable];
    
    
    
    UIButton *textLableBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    textLableBtn.frame = CGRectMake(WIDTH - HEIGHT / 20 - 10, CGRectGetMaxY(backView.frame) +2, 30, HEIGHT / 20);
    [textLableBtn addTarget:self action:@selector(imageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    textLableBtn.backgroundColor = [UIColor whiteColor];
    [textLableBtn setImage:[UIImage imageNamed:@"service_but_write_pop"] forState:UIControlStateNormal];
    textLableBtn.tag = 3001;
    [self.view addSubview:textLableBtn];
    
    self.textBackView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(textLableBtn.frame)+2, WIDTH, HEIGHT / 5)];
    _textBackView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_textBackView];
    
    
    textVi = [[UITextView alloc] initWithFrame:CGRectMake(5, 0, WIDTH-10, HEIGHT/10)];
//    textVi.backgroundColor = [UIColor redColor];
    [self.textBackView addSubview:textVi];

}
-(void)imageBtnAction:(UIButton *)button{
//    NSLog(@"%ld",(long)button.tag);
    if (3001 == button.tag) {
        self.btmView.frame = CGRectMake(0, SCREENH_HEIGHT/11*6, SCREEN_WIDTH, SCREENH_HEIGHT/11*5);
//        AddDescribeViewController *addDescribeVC = [[AddDescribeViewController alloc] init];
//        [self.navigationController pushViewController:addDescribeVC animated:YES];
    }else{
        if (_imageArray.count >= 6) {
            NSLog(@"最多只能上传9张图片");
        } else {
            [self selectPictures];
        }
        
    }
}
// 本地相册选择多张照片
- (void)selectPictures
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 6-_imageArray.count;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
                              {
                                  if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo])
                                  {
                                      NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                                      
                                      return duration >= 5;
                                  } else {
                                      return YES;
                                  }
                              }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}
// 9宫格图片布局
- (void)nineGrid
{
    for (UIImageView *imgv in _editv.subviews)
    {
        if ([imgv isKindOfClass:[UIImageView class]]) {
            [imgv removeFromSuperview];
        }
    }
    
    CGFloat width = kUIScreenWidth/5;
    CGFloat widthSpace = (WIDTH - 15*4 - (kUIScreenWidth/5.5
)*4) / 3.0;
    CGFloat heightSpace = 10;
    
    NSInteger count = _imageArray.count;
    _imageArray.count > 6 ? (count = 6) : (count = _imageArray.count);
    
    for (int i=0; i<count; i++)
    {
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(15+(width+widthSpace)*(i%4), (i/4)*(width+heightSpace) +15, width, width)];
        imgv.image = _imageArray[i];
        imgv.userInteractionEnabled = YES;
        [_editv addSubview:imgv];
        
        //        UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
        //        delete.frame = CGRectMake(width-16, 0, 16, 16);
        ////        delete.backgroundColor = [UIColor greenColor];
        //        [delete addTarget:self action:@selector(deleteEvent:) forControlEvents:UIControlEventTouchUpInside];
        //        delete.tag = 10+i;
        //        [delete setImage:[UIImage imageNamed:@"else_but_closepop@2x"] forState:UIControlStateNormal];
        //        [imgv addSubview:delete];
        
        if (i == _imageArray.count - 1)
        {
            if (_imageArray.count % 4 == 0) {
                _addPic.frame = CGRectMake(15, CGRectGetMaxY(imgv.frame) + heightSpace, 70, 70);
            } else {
                _addPic.frame = CGRectMake(CGRectGetMaxX(imgv.frame) + widthSpace, CGRectGetMinY(imgv.frame), 70, 70);
            }
            
            _editv.frame = CGRectMake(0, CGRectGetMaxY(self.backView.frame) +22 + HEIGHT/20 + [UIScreen mainScreen].bounds.size.width/4 + HEIGHT / 20 + HEIGHT/20 , WIDTH, CGRectGetMaxY(_addPic.frame)+20);
            starLabel.frame = CGRectMake(20, _editv.frame.size.height-105, WIDTH, 20);
//            starRatingView.frame = CGRectMake(20, _editv.frame.size.height-75, 200, 25);
        }
    }
}

// 删除照片
//- (void)deleteEvent:(UIButton *)sender
//{
//    UIButton *btn = (UIButton *)sender;
//    [_imageArray removeObjectAtIndex:btn.tag-10];
//
//    [self nineGrid];
//
//    if (_imageArray.count == 0)
//    {
//        _addPic.frame = CGRectMake(15, CGRectGetMaxY(_textView.frame)+15, 70, 70);
//        _editv.frame = CGRectMake(0, 95, ScreenWidth, CGRectGetMaxY(_addPic.frame)+20+50);
//    }
//}

#pragma mark - ZYQAssetPickerController Delegate

- (void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                   {
                       for (int i=0; i<assets.count; i++)
                       {
                           ALAsset *asset = assets[i];
                           UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
                           [_imageArray addObject:tempImg];
                           
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [self nineGrid];
                           });
                       }
                   });
}


// 地址UI
-(void)addAddressUI{
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.textBackView.frame)-55, WIDTH, HEIGHT / 11)];
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 5, HEIGHT/22, HEIGHT/22);
    [btn addTarget:self action:@selector(sendAddressAction) forControlEvents:UIControlEventTouchUpInside];
//    btn.backgroundColor = [UIColor redColor];
    [btn setImage:[UIImage imageNamed:@"else_icon_map"] forState:UIControlStateNormal];
    [backView addSubview:btn];
    
    alable = [[UILabel alloc] initWithFrame:CGRectMake(HEIGHT/22, 0, WIDTH - HEIGHT /11, HEIGHT/11)];
//    lable.backgroundColor = [UIColor redColor];
    alable.text = addressString;
    alable.numberOfLines = 0;
    [backView addSubview:alable];
    alable.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(label)];
    [alable addGestureRecognizer:tap];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(WIDTH -HEIGHT/11 + HEIGHT/22, 0, HEIGHT/22, HEIGHT/11);
    [rightBtn addTarget:self action:@selector(sendAddressAction) forControlEvents:UIControlEventTouchUpInside];
//    rightBtn.backgroundColor = [UIColor redColor];
    [rightBtn setImage:[UIImage imageNamed:@"but_go"] forState:UIControlStateNormal];
    [backView addSubview:rightBtn];
}
-(void)sendAddressAction{
    
}
//发布维修需求
-(void)sendRepairUI{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(0, HEIGHT - 50-64, WIDTH, 50);
    [btn addTarget:self action:@selector(sendRepairAction) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor colorWithRed:255/255.0 green:114/255.0 blue:130/255.0 alpha:1.000];
    [btn setTitle:@"发布维修需求" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:btn];

}
-(void)label{
    AddressViewController *add = [[AddressViewController alloc] init];
    [add blockstring:^(NSInteger str, NSString *address, NSString *name, NSString *tel) {
        num = str;
        alable.text = [NSString stringWithFormat:@"%@ %@ %@",name,tel,address];
        
    }];
    [self.navigationController pushViewController:add animated:YES];
    
}
-(void)sendRepairAction{
    [AppTools createAFN:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=InsertRepair&repaircontent=%@&addressid=%ld&userid=%@",textVi.text,num,USERID] success:^(id result) {
        
        NSLog(@"%@%@",result,[result[0] objectForKey:@"RepairId"]);
        for (int i = 0; i<_imageArray.count; i++) {
            NSData *fileData = UIImageJPEGRepresentation(_imageArray[i ], 1.0);
            NSString *encodedString = [fileData base64Encoding];
            NSDictionary *dic = @{@"RepairId":[result[0] objectForKey:@"RepairId"],@"Code":encodedString,@"Userid":USERID};
            [AppTools postData:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=InsertRepairImage&"] from:^(id data) {
                
                
            } dic:dic success:^(id result) {
                NSLog(@"%@",result);
                
            } error:^(NSError *error) {
                //            NSLog(@"%@",error);
                
            }];
            
            
        }
        
        
    } error:^(NSError *error) {
        
        
    }];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
